<template>
  <div class="app-container">
    <el-form ref="userForm" :model="dialogForm" :rules="formRules" label-width="110px">
      <el-row class="form_table">
        <el-col :span="12">
          <el-form-item :label="$t('interface.name')" prop="infNameName">
            <el-input v-model.trim="dialogForm.infNameName" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('interface.infNameBiaoshi')" prop="infName">
            <el-input v-model="dialogForm.infName" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row class="form_table">
        <el-col :span="12">
          <el-form-item :label="$t('role.Subordinate')" prop="withGroup">
            <el-select v-model="dialogForm.withGroup" clearable="clearable" filterable remote reserve-keyword :placeholder="$t('table.pleaseSelect')">
              <el-option v-for="item in menus" :key="item.id" :label="item.text" :value="item.id" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('apiList.desc')" prop="infDescription">
            <el-input v-model="dialogForm.infDescription" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row class="form_table">
        <el-col :span="24">
          <el-form-item :label="$t('interface.SQLsentence')" prop="sqlSentence">
            <el-input v-model="dialogForm.sqlSentence" type="textarea" rows="4" />
          </el-form-item>
        </el-col>
      </el-row>
      <!-- Container start-->
      <div class="ParyDiv">
        <div class="title" style="border-bottom: 1px dashed #ccc; line-height: 32px; margin-top: 50px">
          <div class="titleStyle">
            <span class="titleStr">
              <span class="spanDiv">
                <a v-if="isContainerIcon" />
                <a v-else />
                {{ $t('interface.requiredParameter') }}
              </span>
            </span>
            <el-button class="filter-item buttonClass" style="float: right" type="warning" icon="el-icon-plus" @click="addContainerData">{{ $t('table.add') }}</el-button>
          </div>
        </div>
        <div v-if="isContainer">
          <el-table :data="containerData" class="custom-table">
            <el-table-column :label="$t('interface.parameter')">
              <template slot-scope="scope">
                <div v-if="scope.row.isEdit">
                  <el-input v-model="scope.row.paramName" />
                </div>
              </template>
            </el-table-column>
            <el-table-column :label="$t('interface.Type')">
              <template slot-scope="scope">
                <div v-if="scope.row.isEdit">
                  <el-input v-model="scope.row.dataType" />
                </div>
              </template>
            </el-table-column>
            <el-table-column :label="$t('interface.rule')">
              <template slot-scope="scope">
                <div v-if="scope.row.isEdit">
                  <el-checkbox v-model="scope.row.require" />
                </div>
              </template>
            </el-table-column>
            <el-table-column :label="$t('interface.sampleValue')">
              <template slot-scope="scope">
                <div v-if="scope.row.isEdit">
                  <el-input v-model="scope.row.paramDemo" />
                </div>
              </template>
            </el-table-column>
            <el-table-column :label="$t('interface.parametricDescription')">
              <template slot-scope="scope">
                <div v-if="scope.row.isEdit">
                  <el-input v-model="scope.row.description" />
                </div>
              </template>
            </el-table-column>
            <el-table-column :label="$t('table.operation')">
              <template slot-scope="scope">
                <img class="imagedelete" src="../../../../assets/images/pick_up.png" @click="deletecontainerData(scope, scope.$index, 'containerData')">
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
      <!-- 响应参数 start-->
      <div class="ParyDiv">
        <div class="title" style="border-bottom: 1px dashed #ccc; line-height: 32px">
          <div class="titleStyle">
            <span class="titleStr">
              <span class="spanDiv"> {{ $t('interface.responseParameter') }} </span>
            </span>
            <el-button class="filter-item buttonClass" style="float: right" type="warning" icon="el-icon-plus" @click="addResponseData">{{ $t('table.add') }}</el-button>
          </div>
        </div>
        <div v-if="isContainer">
          <el-table :data="responseData" class="custom-table">
            <el-table-column :label="$t('interface.parameter')">
              <template slot-scope="scope">
                <div v-if="scope.row.isEdit">
                  <el-input v-model="scope.row.map" />
                </div>
              </template>
            </el-table-column>
            <el-table-column :label="$t('systemRules.paramType')">
              <template slot-scope="scope">
                <div v-if="scope.row.isEdit">
                  <el-input v-model="scope.row.type" />
                </div>
              </template>
            </el-table-column>
            <el-table-column :label="$t('interface.MapFields')">
              <template slot-scope="scope">
                <div v-if="scope.row.isEdit">
                  <el-input v-model="scope.row.name" />
                </div>
              </template>
            </el-table-column>
            <el-table-column :label="$t('interface.parametricDescription')">
              <template slot-scope="scope">
                <div v-if="scope.row.isEdit">
                  <el-input v-model="scope.row.desc" />
                </div>
              </template>
            </el-table-column>
            <el-table-column :label="$t('table.operation')">
              <template slot-scope="scope">
                <img class="imagedelete" src="../../../../assets/images/pick_up.png" @click="deletecontainerData(scope, scope.$index, 'responseData')">
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
      <!-- 响应结果 -->
      <el-card shadow="hover" class="ms_card">
        <div slot="header" class="clearfix">
          <span style="line-height: 28px">{{ $t('interface.responseResults') }}</span>
          <el-button size="mini" class="fr" type="primary" @click="beautiful">{{ $t('interface.formatting') }}</el-button>
          <el-button size="mini" style="margin-right: 8px" class="fr" type="primary" @click="testDemoFun">{{ $t('btn.test') }}</el-button>
        </div>
        <el-form-item prop="responseDemo" style="height: 260px" label-width="0">
          <el-input v-model="dialogForm.responseDemo" type="textarea" :rows="12" />
        </el-form-item>
      </el-card>
    </el-form>
    <el-button v-permission="'gaeaSettingController#insert'" style="float: right" type="warning" @click="$router.back(-1)"> {{ $t('btn.back') }} </el-button>
    <el-button v-permission="'gaeaSettingController#insert'" style="float: right; margin-right: 8px" type="primary" @click="confirmAdd('保存')"> {{ $t('btn.confirmP') }} </el-button>
  </div>
</template>

<script>
import { pageList, businessApplication, addApplication, deleteApplication, online, offline, testDemo, authorization, queryPowerFun, submitPowerFun, interfaceDetail, editApplication } from '@/api/generator/interface'
import { getDictList } from '@/api/dict-data'
export default {
  data() {
    return {
      dialogPowerVisible: false,
      menus: [],
      powerForm: {
        respExample: '',
      },
      powerData: [],
      savePowerDate: [],
      appIds: [],
      isDisabled: true,
      appIdStatus: false,
      confirmStatus: false,
      isContainer: true,
      isContainerIcon: false,
      isTest: false,
      containerData: [],
      responseData: [],
      TestData: [],
      selectedList: [],
      formRules: {
        infNameName: [{ required: true, message: this.$t('placeholder.input'), trigger: 'blur' }],
        infName: [{ required: true, message: this.$t('placeholder.input'), trigger: 'blur' }],
        withGroup: [{ required: true, message: this.$t('placeholder.select'), trigger: 'blur' }],
        sqlSentence: [{ required: true, message: this.$t('placeholder.input'), trigger: 'blur' }],
      },
      params: {
        pageNumber: 1,
        pageSize: 10,
        appName: '',
        appId: '',
        appSecret: '',
      },
      list: null,
      totalCount: 0,
      authorizedName: '',
      totalPage: 0,
      listLoading: true,
      // 项目基础配置
      basicDialog: false,
      testDialog: false,
      dailogName: '',
      dialogForm: {
        appId: '',
        appName: '',
        status: '',
        remark: '',
      },
    }
  },
  watch: {},
  created() {
    this.interfaceDetailFun()
    getDictList('INF_WITH_GROUP').then(({ data }) => {
      this.menus = data
    })
  },
  methods: {
    async testDemoFun() {
      const TestDataPar = {}
      this.containerData.map((item, index) => {
        const itemKey = item.paramName
        TestDataPar[itemKey] = item.paramDemo
      })
      // const TestDataCopy = JSON.stringify(TestDataPar)
      this.dialogForm.queryParams = TestDataPar
      this.dialogForm.requestParams = JSON.stringify(this.containerData)
      this.dialogForm.responseParams = JSON.stringify(this.responseData)
      const res = await testDemo(this.dialogForm)
      if (res.code != '200') return
      this.$forceUpdate()
      this.dialogForm.responseDemo = JSON.stringify(res.data)
    },
    beautiful() {
      this.$forceUpdate()
      this.dialogForm.responseDemo = this.getFormatData(this.dialogForm.responseDemo)
    },
    /**
     * JOSN数据格式化
     * @param  json
     */
    getFormatData(json) {
      // eslint-disable-next-line no-redeclare
      var json = json + ''
      if (json.indexOf('{') == -1 && json.indexOf('[') == -1) {
        return json
      } else {
        return this.formatJson(json)
      }
    },
    formatJson(json) {
      // eslint-disable-next-line one-var
      var i = 0,
        il = 0,
        tab = '    ',
        newJson = '',
        indentLevel = 0,
        inString = false,
        currentChar = null
      for (i = 0, il = json.length; i < il; i += 1) {
        currentChar = json.charAt(i)
        switch (currentChar) {
          case '{':
          case '[':
            if (!inString) {
              newJson += currentChar + '\n' + this.repeat(tab, indentLevel + 1)
              indentLevel += 1
            } else {
              newJson += currentChar
            }
            break
          case '}':
          case ']':
            if (!inString) {
              indentLevel -= 1
              newJson += '\n' + this.repeat(tab, indentLevel) + currentChar
            } else {
              newJson += currentChar
            }
            break
          case ',':
            if (!inString) {
              newJson += ',\n' + this.repeat(tab, indentLevel)
            } else {
              newJson += currentChar
            }
            break
          case ':':
            if (!inString) {
              newJson += ': '
            } else {
              newJson += currentChar
            }
            break
          case ' ':
          case '\n':
          case '\t':
            if (inString) {
              newJson += currentChar
            }
            break
          case '"':
            if (i > 0 && json.charAt(i - 1) !== '\\') {
              inString = !inString
            }
            newJson += currentChar
            break
          default:
            newJson += currentChar
            break
        }
      }
      return newJson
    },
    repeat(s, count) {
      return new Array(count + 1).join(s)
    },
    async interfaceDetailFun() {
      const ids = this.$route.query.id
      if (!ids) return
      const res = await interfaceDetail(ids)
      if (res.code != '200') return
      this.dialogForm = res.data
      window.data = res.data
      this.responseData = JSON.parse(res.data.responseParams)
      this.containerData = JSON.parse(res.data.requestParams)
    },
    addResponseData() {
      // 新增一条空表单
      this.responseData.push({
        name: null,
        desc: null,
        type: null,
        map: null,
        isEdit: true,
      })
    },
    deletecontainerData(row, index, name) {
      this[name].splice(index, 1)
    },
    // 新增按钮
    confirmAdd() {
      this.$refs.userForm.validate(async(valid, obj) => {
        if (valid) {
          this.dialogForm.requestParams = JSON.stringify(this.containerData)
          this.dialogForm.responseParams = JSON.stringify(this.responseData)
          if (this.$route.query.id) {
            const { code } = await editApplication(this.dialogForm)
            if (code != '200') return
            this.$store.state.tagsView.visitedViews.splice(
              this.$store.state.tagsView.visitedViews.findIndex((item) => item.path === this.$route.path),
              1
            )
            this.$router.back()
          } else {
            const { code } = await addApplication(this.dialogForm)
            if (code != '200') return
            this.$store.state.tagsView.visitedViews.splice(
              this.$store.state.tagsView.visitedViews.findIndex((item) => item.path === this.$route.path),
              1
            )
            this.$router.back()
          }
        } else {
          return
        }
      })
    },
    TestFunction() {
      this.isTest = !this.isTest
    },
    addContainerData() {
      // 新增一条空表单
      this.containerData.push({
        paramName: null,
        description: null,
        dataType: null,
        paramDemo: null,
        sort: null,
        checkRule: null,
        isEdit: true,
      })
    },
    // 选择项改变时
    handleSelectionChange(val) {
      this.selectedList = val
    },
    // 删除操作
    async handleDelete() {
      const ids = this.selectedList.map((item) => item.id)
      const { code } = await deleteApplication(ids)
      // const { code } = await deleteUser(this.selectedList[0].id) // 暂时保留单删接口
      if (code != '200') return
      this.queryByPage()
    },
    // 查询
    search(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          console.log('submit!')
          this.queryByPage()
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    // 重置
    reset(formName) {
      this.$refs[formName].resetFields()
      this.params.userName = ''
      this.params.pageTitle = ''
      this.params.requestUrl = ''
      this.queryByPage()
    },
    async queryByPage() {
      const res = await pageList(this.params)
      if (res.code != '200') return
      this.listLoading = true
      this.list = res.data.records
      this.totalCount = res.data.total
      this.totalPage = res.data.pages
      this.listLoading = false
    },
    handleSizeChange(val) {
      this.params.pageSize = val
      this.queryByPage()
    },
    handleCurrentChange(val) {
      this.params.pageNumber = val
      this.queryByPage()
    },
  },
}
</script>
<style scoped lang="scss">
.header {
  line-height: 40px;
  font-weight: bold;
  text-indent: 3rem;
  background: #f9fcff;
  margin-bottom: 5px;
}
.imagedelete {
  width: 15px;
  margin-top: 6px;
}
</style>
